import { FC, useEffect, useState } from "react";

// 引入资源
import styles from './styles.module.scss'
import { Link, useSearchParams } from "react-router-dom";
import { Breadcrumb, Button, message } from "antd";
import recommend from '@/assets/Product/recommend.svg'
import classNames from "classnames";
// 引入请求
import { reqGoodsInfo, reqHotRecommend, reqGoodsComment, reqCommentDetail } from "../../api/Product";
import { reqAddCartList } from "../../api/CartList";
// 引入类型
import { GoodsInfoData, HotRecommendResult, GoodsCommentResult, CommentDetailType, CommentItem } from "../../api/Product/type";
import { magnifierType, MaskStyleType, selectSkuType } from "./type";

const Product: FC = () => {

    const [Goods, SetGoods] = useState<GoodsInfoData>()
    const getGoodsInfo = () => {
        reqGoodsInfo(id as string).then((res) => {
            // console.log('商品详细', res.result)
            SetGoods(res.result)
            setBigImg(res.result.mainPictures[0])
        })
    }

    const [searchParams] = useSearchParams()
    const id = searchParams.get('id')

    // 改变商品详细还是商品评论的总按钮
    const [active, setActive] = useState<string>('goodsDetail')

    // 筛选商品评论的按钮
    const [commentActive, setCommentActive] = useState<string>('allComment')

    // 添加评论排序状态
    const [sortActive, setSortActive] = useState<string>('default')  // 默认为"热门"排序

    // 24，周，总榜
    const [HotGoods24, setHotGoods24] = useState<HotRecommendResult[]>([])
    const [HotGoodsWeek, setHotGoodsWeek] = useState<HotRecommendResult[]>([])
    const [HotGoodsAll, setHotGoodsAll] = useState<HotRecommendResult[]>([])
    const getHotRecommend = () => {
        reqHotRecommend(id as string, 4, 1).then((res) => {
            setHotGoods24(res.result)
        })
        reqHotRecommend(id as string, 4, 2).then((res) => {
            setHotGoodsWeek(res.result)
        })
        reqHotRecommend(id as string, 4, 3).then((res) => {
            setHotGoodsAll(res.result)
        })
    }


    // 遮罩样式
    const [maskStyle, setMaskStyle] = useState<MaskStyleType>()

    // 放大器样式
    const [magnifier, setMagnifier] = useState<magnifierType>({
        visibility: 'hidden',
        pointerEvents: 'none',
        zIndex: 0
    })

    // 大图
    const [bigImg, setBigImg] = useState<string>('')

    const [count, setCount] = useState<number>(1)

    // 添加 skuId 状态
    const [currentSkuId, setCurrentSkuId] = useState<string>('')

    // 遮罩层移动
    const maskMove = (e: any) => {
        const bigImgBox = e.currentTarget; // 获取包含大图的容器  
        const { left, top } = bigImgBox.getBoundingClientRect(); // 获取边界信息
        // 计算鼠标相对于大图的位置  
        let x = e.clientX - left - 100;
        let y = e.clientY - top - 100;
        if (x < 0) {
            x = 0
        }
        else if (x > 200) {
            x = 200
        }
        if (y < 0) {
            y = 0
        }
        else if (y > 200) {
            y = 200
        }

        setMaskStyle({ left: x, top: y, display: 'block' })
        setMagnifier({
            visibility: 'visible',
            pointerEvents: 'auto',
            backgroundImage: `url(${bigImg})`,
            backgroundPosition: `${-2 * x}px ${-2 * y}px`,
            zIndex: 999
        })
    }

    // 离开遮罩层

    const maskLeave = () => {
        setMaskStyle({ display: 'none' })
        setMagnifier({
            visibility: 'hidden',
            pointerEvents: 'none',
            zIndex: 0
        })
    }




    // 加入购物车

    // const [selectSku, setSelectSku] = useState<selectSkuType[]>([])

    const [selectSku, setSelectSku] = useState<selectSkuType[]>([])

    // 在商品信息加载完成后，自动选中每个规格的第一个选项
    useEffect(() => {
        if (Goods?.specs) {
            const initialSkus = Goods.specs.map(spec => ({
                name: spec.name,
                valueName: spec.values[0].name
            }))
            setSelectSku(initialSkus)

            // 设置默认 skuId（第一个 sku）
            if (Goods.skus && Goods.skus.length > 0) {
                setCurrentSkuId(Goods.skus[0].id)
            }
        }
    }, [Goods])

    // 修改 selectSkuChange 函数
    const selectSkuChange = (name: string, valueName: string) => {
        const existingIndex = selectSku.findIndex(item => item.name === name)
        if (existingIndex > -1) {
            const newSelectSku = [...selectSku]
            newSelectSku[existingIndex] = { name, valueName }
            setSelectSku(newSelectSku)

            // 根据选择的规格找到对应的 sku
            if (Goods?.skus) {
                const matchingSku = Goods.skus.find(sku =>
                    sku.specs.every(spec => {
                        const selectedSpec = newSelectSku.find(s => s.name === spec.name)
                        return selectedSpec && selectedSpec.valueName === spec.valueName
                    })
                )
                if (matchingSku) {
                    setCurrentSkuId(matchingSku.id)
                }
            }
        } else {
            const newSelectSku = [...selectSku, { name, valueName }]
            setSelectSku(newSelectSku)
        }
    }
    const [messageApi, contextHolder] = message.useMessage();
    const addCart = () => {
        if (!currentSkuId) {
            // console.log('请选择商品规格')
            return
        }
        // console.log('加入购物车', { skuId: currentSkuId, count })
        reqAddCartList({ skuId: currentSkuId, count }).then(() => {

            message.success('加入购物车成功!', 1, () => {

            })
        }).catch(() => {
            message.error('加入购物车失败！！！', 1, () => {

            })
        })
    }

    // 评论模块
    const [commentTag, setCommentTag] = useState<GoodsCommentResult>()
    const [commentDetail, setCommentDetail] = useState<CommentDetailType>()
    // 获取评论Tag
    const getCommentTag = () => {
        reqGoodsComment(id as string).then((res) => {
            setCommentTag(res.result)

        })
    }
    // 获取评论分页
    const getCommentDeatil = () => {
        reqCommentDetail(id as string, 1, 10, false).then((res) => {
            console.log('评论详细', res.result)
            setCommentDetail(res.result)

        })
    }
    useEffect(() => {
        if (id) {
            getGoodsInfo()
            getHotRecommend()
            getCommentTag()
            getCommentDeatil()
        }
        return () => {
            // cleanup if needed
        }
    }, [id]) // 添加 id 作为依赖项

    useEffect(() => {
        // console.log('selectSku已更新为:', selectSku)
    }, [selectSku])

    return (
        <div className={styles.Product}>
            {contextHolder}
            {/* 面包屑 */}
            <div className={styles.bread}>
                <Breadcrumb
                    items={[
                        {
                            title: <Link to={'/home'}>首页</Link>,
                        },
                        {
                            title: <Link to={`/category?id=${Goods?.categories[1].id}`} > {Goods?.categories[1].name}</Link>
                        },
                        {
                            title: <Link to={`/category/sub?id=${Goods?.categories[0].id}`} > {Goods?.categories[0].name}</Link>
                        },
                        {
                            title: Goods?.name,
                        },
                    ]}
                />
            </div>
            {/* 商品选择 */}
            <div className={styles.goodSelect}>
                <div className={styles.left}>
                    <div className={styles.img}>
                        <div className={styles.bigImgBox} onMouseMove={(e) => {
                            maskMove(e)
                        }}
                            onMouseLeave={() => {
                                maskLeave()
                            }}
                        >
                            <img src={bigImg} alt="" className={styles.bigImg} />
                            <span style={maskStyle}></span>
                        </div>
                        {/* 放大镜 */}
                        <div className={styles.magnifier} style={magnifier}>
                            <span style={magnifier} ></span>
                        </div>
                        <div>
                            {
                                Goods?.mainPictures.map((pic) => {
                                    return (
                                        <img src={pic} alt="" key={pic} onMouseEnter={() => {
                                            setBigImg(pic)
                                        }} />
                                    )
                                })
                            }

                        </div>
                    </div>
                    <div className={styles.info}>
                        <div>
                            <span>销量人气</span>
                            <span>200+</span>
                            <span>销量人气</span>
                        </div>
                        <div>
                            <span>商品评价</span>
                            <span>400+</span>
                            <span>查看评价</span>
                        </div>
                        <div>
                            <span>收藏人气</span>
                            <span>600+</span>
                            <span>收藏商品</span>
                        </div>
                        <div>
                            <span>品牌信息</span>
                            <span>LPYTR品牌</span>
                            <span>品牌主页</span>
                        </div>
                    </div>
                </div>
                <div className={styles.right}>
                    <div className={styles.desc}>
                        <span>{Goods?.name}</span>
                        <span>{Goods?.desc}</span>
                        <div><span>{Goods?.price}</span><span>{Goods?.oldPrice}</span></div>
                    </div>
                    <div className={styles.service}>
                        <div>
                            <span>促销</span><span>12月好物放送,App领券购买直降120元</span>
                        </div>
                        <div>
                            <span>配送</span><span>至  北京市 市辖区 东城区</span>
                        </div>
                        <div>
                            <span>服务</span><span>无忧退货 快速退款 免费包邮</span>
                        </div>
                    </div>
                    <div className={styles.sku}>
                        {
                            Goods?.specs.map((spec) => {
                                return (
                                    <div key={spec.name}>
                                        <span>{spec.name}</span>
                                        <div>
                                            {spec.values.map((value) => {
                                                // 检查当前选项是否被选中
                                                const isSelected = selectSku.some(item =>
                                                    item.name === spec.name && item.valueName === value.name
                                                )

                                                if (value.picture) {
                                                    return (
                                                        <img
                                                            src={value.picture}
                                                            alt={value.desc}
                                                            key={value.name}
                                                            onClick={() => {
                                                                selectSkuChange(spec.name, value.name)
                                                            }}
                                                            className={classNames({ [styles.active]: isSelected })}
                                                        />
                                                    )
                                                } else {
                                                    return (
                                                        <span
                                                            title={value.desc}
                                                            key={value.name}
                                                            onClick={() => {
                                                                selectSkuChange(spec.name, value.name)
                                                            }}
                                                            className={classNames({ [styles.active]: isSelected })}
                                                        >
                                                            {value.name}
                                                        </span>
                                                    )
                                                }
                                            })}
                                        </div>
                                    </div>
                                )
                            })
                        }

                    </div>
                    <div className={styles.numberBox}>
                        <span>数量：</span>
                        <div>
                            <span onClick={() => {
                                setCount(count => Math.max(--count, 0))

                            }} style={{ cursor: count === 0 ? 'not-allowed' : 'pointer' }}>-</span>
                            <span>{count}</span>
                            <span onClick={() => {
                                setCount(count => ++count)
                            }}>+</span>
                        </div>
                    </div>
                    <div className={styles.addButton}>
                        <Button type="primary" onClick={() => {
                            addCart()
                        }}>加入购物车</Button>
                    </div>
                </div>
            </div>
            {/* 同类商品推荐 */}
            <div className={styles.goodsLike}>

                <span className={styles.title}>
                    <img src={recommend} alt="" />同类商品推荐
                </span>
                <div>
                    {Goods?.similarProducts.map((similar) => {
                        return (
                            <li key={similar.id}>
                                <img src={similar.picture} alt="" />
                                <span>{similar.name}</span>

                                <span>￥{similar.price}</span>
                            </li>
                        )
                    })}
                </div>
            </div>
            {/* 商品详细，24小时热销榜，周热销榜 */}
            <div className={styles.contentBox}>
                <div className={styles.goodsDetail}>
                    <div className={styles.title}>
                        <span className={active === 'goodsDetail' ? styles.active : ''} onClick={() => {
                            setActive('goodsDetail')
                        }}>商品详情</span>

                        <span className={active === 'goodsComment' ? styles.active : ''} onClick={() => {
                            setActive('goodsComment')
                        }}>商品评论</span>
                    </div>
                    {/* 商品详情 */}
                    {active === 'goodsDetail' && (
                        <div className={styles.goodsDetailContent}>
                            <div className={styles.attrs}>
                                {
                                    Goods?.details.properties.map((prop) => {
                                        return (
                                            <div key={prop.name}>
                                                <div>{prop.name}</div>
                                                <div>{prop.value}</div>
                                            </div>
                                        )
                                    })
                                }


                            </div>

                            <div className={styles.imgs}>
                                {Goods?.details.pictures.map((pic) => {
                                    return (
                                        <img key={pic} src={pic} alt="" />
                                    )
                                })}
                            </div>
                        </div>
                    )}
                    {/* 商品评论 */}
                    {active === 'goodsComment' && (
                        <div className={styles.goodsComment}>
                            <div className={styles.left}>
                                <div>
                                    <span>{commentTag?.salesCount}+</span>
                                    <br />
                                    <span>人购买</span>
                                </div>
                                <div>
                                    <span>{commentTag?.praisePercent}%</span>
                                    <br />
                                    <span>好评率</span>
                                </div>

                            </div>
                            <div className={styles.right}>

                                <span className={commentActive === 'allComment' ? styles.active : ''} onClick={() => {
                                    setCommentActive('allComment')
                                }
                                } >全部评价（{commentTag?.evaluateCount}）</span>
                                <span className={commentActive === 'hasPicture' ? styles.active : ''} onClick={() => {
                                    setCommentActive('hasPicture')
                                }}>有图（{commentTag?.hasPictureCount}）</span>
                                <span className={commentActive === 'goodComment' ? styles.active : ''} onClick={() => {
                                    setCommentActive('goodComment')
                                }}>音质好</span>
                                <span className={commentActive === 'fastCharge' ? styles.active : ''} onClick={() => {
                                    setCommentActive('fastCharge')
                                }}>充电快</span>
                                <span className={commentActive === 'softMaterial' ? styles.active : ''} onClick={() => {
                                    setCommentActive('softMaterial')
                                }}>材质很软</span>
                                <span className={commentActive === 'highCostPerformance' ? styles.active : ''} onClick={() => {
                                    setCommentActive('highCostPerformance')
                                }}>性价比高</span>
                            </div>
                            <div className={styles.sortTag}>
                                <div>排序：
                                    <span
                                        className={sortActive === 'default' ? styles.active : ''}
                                        onClick={() => {
                                            setSortActive('default')
                                        }}
                                    >
                                        默认
                                    </span>
                                    <span
                                        className={sortActive === 'theHottest' ? styles.active : ''}
                                        onClick={() => {
                                            setSortActive('theHottest')
                                        }}
                                    >
                                        最热
                                    </span>
                                    <span
                                        className={sortActive === 'upToDate' ? styles.active : ''}
                                        onClick={() => {
                                            setSortActive('upToDate')
                                        }}
                                    >
                                        最新
                                    </span>
                                </div>
                            </div>
                            <div className={styles.commentContent}>
                                {
                                    commentDetail?.items.map((comment: CommentItem) => {
                                        return (
                                            <div className={styles.item} key={comment.id}>
                                                <div className={styles.left}>
                                                    <img src={comment?.member?.avatar} alt="" />
                                                    <span>{comment?.member?.nickname}</span>
                                                </div>
                                                <div className={styles.right}>
                                                    <div className={styles.specifications}>
                                                        <span>评分：{comment?.score}</span>
                                                        <span>{comment?.orderInfo?.name}</span>
                                                    </div>
                                                    <span className={styles.content}>
                                                        {comment?.content}
                                                    </span>
                                                    <div className={styles.dateAndgiveTheThumbsUp}>
                                                        <span>{comment?.createTime}</span>
                                                        <span>点赞{comment?.praiseCount}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        )

                                    })
                                }



                            </div>

                        </div>
                    )}
                </div>



                <div className={styles.hotSellingList}>

                    {/* 总热榜 */}
                    <div className={styles.title}>
                        <span>总热榜</span>
                    </div>
                    <div className={styles.content}>
                        {HotGoodsAll?.map((hot) => {
                            return (
                                <li key={hot.id}>
                                    <img src={hot.picture} alt="" />
                                    <span>{hot.name}</span>
                                    <span>{hot.desc}</span>
                                    <span>￥{hot.price}</span>
                                </li>
                            )
                        })}
                    </div>
                    {/* 周热榜 */}
                    {/* <div className={styles.title}>
                        <span>一周热榜</span>
                    </div>
                    <div className={styles.content}>
                        {HotGoodsWeek?.map((hot) => {
                            return (
                                <li key={hot.id}>
                                    <img src={hot.picture} alt="" />
                                    <span>{hot.name}</span>
                                    <span>{hot.desc}</span>
                                    <span>￥{hot.price}</span>
                                </li>
                            )
                        })}
                    </div> */}
                    {/* 24小时热榜 */}
                    {/* <div className={styles.title}>
                        <span>24小时热榜</span>
                    </div>
                    <div className={styles.content}>
                        {HotGoods24?.map((hot) => {
                            return (
                                <li key={hot.id}>
                                    <img src={hot.picture} alt="" />
                                    <span>{hot.name}</span>
                                    <span>{hot.desc}</span>
                                    <span>￥{hot.price}</span>
                                </li>
                            )
                        })}
                    </div> */}

                </div>



            </div>
        </div>
    )
}


export default Product